package com.ttxz.sample.view

import android.os.Build
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.hjq.toast.ToastUtils
import com.ttxz.common.base.view.BaseActivity
import com.ttxz.common.base.viewmodel.EmptyViewModel
import com.ttxz.common.utils.log.LogUtil
import com.ttxz.sample.databinding.ActivityWebviewBinding

class WebViewActivity : BaseActivity<ActivityWebviewBinding, EmptyViewModel>() {

    override fun initCustomData() {
        super.initCustomData()

        viewBinding?.btnBack?.setOnClickListener() {
            finish()
        }

        val url = intent.getStringExtra("url")
        val title = intent.getStringExtra("title")

        LogUtil.e("加载Url=$url----title=$title")
        if (url.isNullOrEmpty()) {
            ToastUtils.show("Url地址为空")
            return
        }

        viewBinding?.tvTitle?.text = title

        val webSetting = viewBinding?.webView?.settings
        webSetting?.javaScriptEnabled = true
        // JS打开窗口
        webSetting?.javaScriptCanOpenWindowsAutomatically = true;
        // ===设置JS可用
        // 可以访问文件
        webSetting?.allowFileAccess = true;
        // ===缩放可用
        webSetting?.setSupportZoom(true);
        webSetting?.displayZoomControls = false; //隐藏原生的缩放控件
        webSetting?.layoutAlgorithm =
            WebSettings.LayoutAlgorithm.NARROW_COLUMNS; //设置缩放功能   //能不能缩放 取决于网页设置
        webSetting?.loadWithOverviewMode = true;
        webSetting?.builtInZoomControls = true;
        // ===缩放可用
        // 支持多窗口打开后，点击内部链接会使新窗口打开网页
//        webSetting?.setSupportMultipleWindows(true);
        // ===============缓存
        webSetting?.cacheMode = WebSettings.LOAD_DEFAULT;// 决定是否从网络上取数据。
        webSetting?.setAppCacheEnabled(true);
        // ===============缓存
        webSetting?.useWideViewPort = true;
        webSetting?.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting?.pluginState = WebSettings.PluginState.ON_DEMAND
        // 适配图片加载不出来的问题
        webSetting?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
        webSetting?.domStorageEnabled = true//解决掘金网站显示不出来的问题
        viewBinding?.webView?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                view?.loadUrl(request?.url.toString())
                return true
            }
        }
        viewBinding?.webView?.loadUrl(url)
    }
}